const Koa = require('koa')
const path = require('path')
const koaStatic = require('koa-static')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const redisStore  = require('koa-redis')
const { REDIS_CONF }  = require('./conf/db')
const { COOKIE_SECRET_KEY }  = require('./conf/secret')

// 路由
const user = require('./routes/api/user')
const utils = require('./routes/api/utils')
const blog = require('./routes/api/blog')
const profile = require('./routes/api/profile')
const userRelation = require('./routes/api/userRelation')
const home = require('./routes/api/home')
const atRelation = require('./routes/api/atRelation')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
// app.use(koaStatic(__dirname + '/public'))
app.use(koaStatic(path.join(__dirname, '../', 'public')))


// session
app.keys = [COOKIE_SECRET_KEY] //cookie的密匙
// 挂载session中间件
app.use(session({
  key: 'weibo.sid', //cookie名称key
  prefix: 'weibo:sess:', //session 在仓库里的前缀
  cookie: { //cookie设置
    path: '/', //网站所有路径cookie都生效
    httpOnly: false, //只允许服务端修改cookie
    maxAge: 24 * 60 * 60 * 1000, // 一天,
  },
  store: redisStore({ //session的存储仓库
    all: `${REDIS_CONF.HOST}:${REDIS_CONF.PORT}`
  })
}))

// 模板
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes 
app.use(user.routes(), user.allowedMethods())
app.use(utils.routes(), utils.allowedMethods())
app.use(blog.routes(), blog.allowedMethods())
app.use(profile.routes(), profile.allowedMethods())
app.use(userRelation.routes(), userRelation.allowedMethods())
app.use(home.routes(), home.allowedMethods())
app.use(atRelation.routes(), atRelation.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
